const app = getApp()
const db = wx.cloud.database()
const _ = db.command
let floor = null
let name = null
let date = ''
Page({
  data: {
    totalMoney: 0
  },
  onLoad(opt) {
    console.log(opt)
    floor = opt.floor
    date = opt.date
    name = opt.name
    this.getDetail()
    wx.setNavigationBarTitle({
      title: floor + name,
    })
  },
  getDetail() {
    db.collection('classVenue').where({
        floor: floor,
        name: name,
        timeList: _.not(_.eq(date))
      }).get()
      .then(res => {
        console.log('可预约时间段', res)
        let list = res.data
        list.forEach(item => {
          item.selected = false
        })
        this.setData({
          list: res.data
        })
      })
  },
  // 选中的点击事件
  clickChoose(e) {
    let totalMoney = 0
    let id = e.currentTarget.dataset.id
    let list = this.data.list
    list.forEach(item => {
      if (item._id == id) {
        item.selected = !item.selected
      }

      if (item.selected) {
        totalMoney += 20
      }
    })
    this.setData({
      list,
      totalMoney
    })
  },
  //模拟支付
  pay() {
    if (this.data.totalMoney <= 0) {
      wx.showToast({
        icon: "error",
        title: '请选择时间段',
      })
      return
    }
    wx.showModal({
      title: "提示",
      content: "预约教室请慎重选择",
      confirmText: '确定预约',
      success: res => {
        if (res.confirm) {
          this.addOrder()
        }
      }
    })
  },
  //添加预定
  addOrder() {
    let dataList = []
    let proArr = []
    let user = app.globalData.userInfo
    this.data.list.forEach(item => {
      if (item.selected) {
        dataList.push(item._id)
        console.log('item', item)
        let pro = db.collection('classOrder').add({
          data: {
            venueFloor: floor,
            venueName: item.name,
            venueId: item._id,
            timeSlot: item.timeSlot,
            date: date,
            name: user.name,
            phone: user.phone,
            type: user.type,
            department: user.department,
            status: '待使用',
          }
        })
        proArr.push(pro)
      }
    })
    Promise.all(proArr)
      .then(res => {
        console.log('添加预定成功', res)
        // 全部预定添加成功以后，去改变教室状态
        wx.cloud.callFunction({
          name: 'classVenue',
          data: {
            action: 'reserve',
            list: dataList,
            date: date
          }
        }).then(res => {
          console.log('修改教室状态结果', res)
          wx.showToast({
            title: '预定成功',
          })
          this.getDetail()
        })
      })
      .catch(res => {
        console.log('添加预定失败', res)
      })

  }
})